package com.ruitu.health.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.health.R;
import com.ruitu.health.mvp.model.HomeModel;
import com.ruitu.health.mvp.presenter.HomePresenter;
import com.ruitu.health_2.ui.activity.ChinaCultureActivity;
import com.ruitu.health_2.ui.activity.CouponListActivity;
import com.ruitu.health_2.ui.activity.HealthManageActivity;
import com.ruitu.health_2.ui.activity.MsgActivity;
import com.ruitu.health_2.ui.activity.ReadPartieActivity;
import com.ruitu.health_2.ui.activity.SearchActivity;
import com.ruitu.health_2.ui.common.util.ViewUtil;
import com.ruitu.health_2.ui.mall.MallMainActivity;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.home.Advert;
import com.ruitu.router_module.bean.home.HomeData;
import com.ruitu.router_module.bean.home.Model;
import com.ruitu.router_module.bean.system.ScrollInfo;
import com.ruitu.router_module.support.util.GlideImageLoader;
import com.ruitu.router_module.support.util.TimeUtil;
import com.ruitu.router_module.support.view.MyNestedScrollView;
import com.ruitu.router_module.support.view.OnTabSelectedListenerImpl;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.config.Constants;
import me.dkzwm.widget.srl.indicator.IIndicator;

public class Home2Fragment extends BaseFragment<HomePresenter.HomeP, HomeModel.HomeM> {
    private SmoothRefreshLayout refresh;// 外层刷新控件
    private MyNestedScrollView scroll_view;// 滑动控件
    private FrameLayout home_title_bar_layout;// 主页顶部title
    private View home_title_bar_bg_view;// 顶部title背景view

    private LinearLayout ll_scroll;// 所有滚动的内容
    private LinearLayout scan_layout, ll_search;// 标题栏左上角的,搜索
    private RelativeLayout msg_layout;// 右上角消息
    private TextView tv_location;// 位置/城市

    private Banner banner;
    private ImageView iv_banner_holder;// banner的占位图
    private RecyclerView rcv_10_menu, rcv_model;// 10个菜单项,八大模块

    private ImageView iv_new_1, iv_new_2;// 新人专享左,新人专享右

    private XTabLayout tab, tab_2;// tab tab_2是默认隐藏的tab
    private RelativeLayout rl_tab;// 包含tab_2和下边的分割线的布局
    private RelativeLayout rl_container;// tab下面的容器
    /************************** 上面是view 下面是数据 **************************/
    private HomeData homeData;// 请求的首页数据

    private List<Advert> advertiseList = new ArrayList<>();// banner广告轮播数据

    private MenuAdapter menuAdapter;// 10个菜单项的adapter
    private List<Model> modelList = new ArrayList<>();// 10个菜单项的数据

    public static final String[] HOME_MODELS = {"精选", "读书会", "文章", "积分", "商品"};// 新五大模块的布局 精选 读书会...
    private int topHeight = 0;// 记录页面上部的高度(banner + menu + 左右俩图 + tab + 上下外边距)
    private int pageHeight = 0;// 记录页面的高度


    private int SCREEN_WIDTH = 0;//屏幕的宽度

    public static Home2Fragment newInstance() {
        Bundle args = new Bundle();
        Home2Fragment fragment = new Home2Fragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SCREEN_WIDTH = ScreenUtils.getScreenWidth();//获取屏幕宽度

        Logg.i("time = " + TimeUtil.dealDateFormat("2019-10-29T08:43:07.000+0000"));
    }

    // 请求首页的一些数据
    private void reqData() {
        rxList.add(p.reqHomeData());
    }

    @Override
    public void onReqComplete(int code, boolean isOk, Object data) {
        if (code == 1) {
            refresh.refreshComplete(true, 1000);
            homeData = (HomeData) data;
            modelList = homeData.getModelList();
            advertiseList = homeData.getAdvertList();

            initBanner(advertiseList);// 设置banner
            menuAdapter.setDataList(homeData.getModelList());// 设置菜单模块

            // 设置tab下面的数据
            Arad.bus.post(new EventModel(19110750, homeData));
        }
    }

    private View header1, header2, header3, header4;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home_2, container, false);

        home_title_bar_layout = v.findViewById(R.id.home_title_bar_layout);
        home_title_bar_bg_view = v.findViewById(R.id.home_title_bar_bg_view);
        scan_layout = v.findViewById(R.id.scan_layout);
        tv_location = v.findViewById(R.id.tv_location);
        ll_search = v.findViewById(R.id.ll_search);
        msg_layout = v.findViewById(R.id.msg_layout);
        refresh = v.findViewById(R.id.refresh);
        scroll_view = v.findViewById(R.id.scroll_view);
        ll_scroll = v.findViewById(R.id.ll_scroll);
        tab_2 = v.findViewById(R.id.tab_2);
        rl_tab = v.findViewById(R.id.rl_tab);

        initRefreshView();

        //Banner的布局
        header1 = inflater.inflate(R.layout.home_banner_layout, null, false);
        banner = header1.findViewById(R.id.banner);// Banner布局
        iv_banner_holder = header1.findViewById(R.id.iv_banner_holder);// Banner布局占位图
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) banner.getLayoutParams();
        params.width = SCREEN_WIDTH;
        params.height = params.width * 900 / 1800;// banner的比例是1800 * 900
        banner.setLayoutParams(params);
        iv_banner_holder.setLayoutParams(params);

        //菜单项的布局
        header2 = inflater.inflate(R.layout.home_menu_layout_grid, null, false);
        rcv_10_menu = header2.findViewById(R.id.rcv_10_menu);
        menuAdapter = new MenuAdapter(getActivity());
        GridLayoutManager manager5 = new GridLayoutManager(getActivity(), 4);
        rcv_10_menu.setLayoutManager(manager5);
        rcv_10_menu.setAdapter(menuAdapter);
        for (int i = 0; i < 8; i++) {
            Model model = new Model();
            model.setTitle("加载中");
            modelList.add(model);
        }
        menuAdapter.setDataList(modelList);

        // 新人专享模块 左右两张图片
        header4 = inflater.inflate(R.layout.home_newer_special, null, false);
        iv_new_1 = header4.findViewById(R.id.iv_new_1);
        iv_new_2 = header4.findViewById(R.id.iv_new_2);

        int[] size = ViewUtil.getHomeNewSpecial3Height(SCREEN_WIDTH);
        LinearLayout.LayoutParams paramIvNew = (LinearLayout.LayoutParams) iv_new_1.getLayoutParams();
        paramIvNew.width = size[0];
        paramIvNew.height = size[1];
        iv_new_1.setLayoutParams(paramIvNew);

        LinearLayout.LayoutParams paramIvNew2 = (LinearLayout.LayoutParams) iv_new_2.getLayoutParams();
        paramIvNew2.width = size[0];
        paramIvNew2.height = size[1];
        iv_new_2.setLayoutParams(paramIvNew2);

        // tab五个模块
        header3 = inflater.inflate(R.layout.home_tab_layout, null, false);
        tab = header3.findViewById(R.id.tab);
        rl_container = header3.findViewById(R.id.rl_container);
        for (int i = 0; i < 5; i++) {
            tab.addTab(tab.newTab().setText(HOME_MODELS[i]), i);
            tab_2.addTab(tab_2.newTab().setText(HOME_MODELS[i]), i);
        }

        getFragmentManager().beginTransaction().replace(R.id.rl_container, HomePro0Fragment.newInstance(this), "fragment0").commit();
        scroll_view.post(new TopHeightRunnable());// 计算顶部高度
        scroll_view.post(new PageHeightRunnable());// 计算页面高度

        ll_scroll.addView(header1);// Banner布局
        ll_scroll.addView(header2);// 10个功能菜单布局
        ll_scroll.addView(header4);// 新手专场
        ll_scroll.addView(header3);// 八大模块

        setListeners();//设置一些监听
        reqData();
        hideProgress();
        showProgress();

        return v;
    }

    private void initRefreshView() {
        refresh.setEnableAutoLoadMore(true);
        refresh.setDurationToCloseHeader(500);
        refresh.setDurationOfBackToKeepHeader(300);
        refresh.setEnableOverScroll(false);
//        refresh.setLoadingMinTime(1000);// 最少刷新一秒
        refresh.setMode(Constants.MODE_DEFAULT);// MODE_SCALE 仿小米下拉拉伸页面的效果
    }

    private int scrollY = 0;// 记录下拉的距离

    private void setListeners() {
        menuAdapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {

                if (!isDataEmpty(modelList)) {
                    String id = modelList.get(pos).getId();
                    if (TextUtils.equals("2", id)) {// 商城
                        startActivity(MallMainActivity.class);
                    } else if (TextUtils.equals("3", id)) {// 读书会
                        startActivity(ReadPartieActivity.class);
                    } else if (TextUtils.equals("4", id)) {// 中华文化
                        startActivity(ChinaCultureActivity.class);
                    } else if (TextUtils.equals("5", id)) {// 品味生活

                    } else if (TextUtils.equals("6", id)) {// 健康管理
                        startActivity(HealthManageActivity.class);
                    } else if (TextUtils.equals("7", id)) {// 文化旅行

                    } else if (TextUtils.equals("8", id)) {// 教育文化

                    } else if (TextUtils.equals("9", id)) {// 投资项目

                    }
                } else {
                    ToastUtils.showShortSafe("请稍后重试");
                }
            }
        });
        refresh.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                reqData();
                hideProgress();
                showProgress();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh.refreshComplete(false, 1000);
                    }
                }, 16000);
            }

            @Override
            public void onLoadingMore() {
                Logg.i("refresh加载更多...");
                "".charAt(0);
            }
        });
        refresh.addOnStatusChangedListener(new SmoothRefreshLayout.OnStatusChangedListener() {
            @Override
            public void onStatusChanged(byte old, byte now) {
//                Logg.i("onStatusChanged... old = " + old + ",now = " + now);
                if (now == SmoothRefreshLayout.SR_STATUS_INIT) {// 正常状态,显示搜索栏
                    showTitleBar(true);
                } else if (now == SmoothRefreshLayout.SR_STATUS_PREPARE) {// 正在下拉
                    showTitleBar(false);
                } else if (now == SmoothRefreshLayout.SR_STATUS_REFRESHING) {// 正在刷新
                    showTitleBar(false);
                } else if (now == SmoothRefreshLayout.SR_STATUS_COMPLETE) {// 刷新完成(还没有恢复)
                    showTitleBar(false);
                } else if (now == SmoothRefreshLayout.SR_STATUS_LOADING_MORE) {// 看意思是加载更多
                    showTitleBar(true);
                }
            }
        });
        refresh.addOnNestedScrollChangedListener(new SmoothRefreshLayout.OnNestedScrollChangedListener() {
            @Override
            public void onNestedScrollChanged() {
//                Logg.i("onNestedScrollChanged...");
            }
        });
        refresh.addOnUIPositionChangedListener(new SmoothRefreshLayout.OnUIPositionChangedListener() {
            @Override
            public void onChanged(byte status, IIndicator indicator) {
                // 这个回调和addOnStatusChangedListener回调的状态值是一样的
                // 区别:OnStatusChanged状态相同时不执行,只有状态改变时执行 onChanged:一直回调当前状态
//                Logg.i("OnUIPositionChanged... status = " + status);
//                Logg.i("indicator.getRawOffset()  = " + indicator.getRawOffset());

//                if ((status == SmoothRefreshLayout.SR_STATUS_PREPARE)
//                        && (scrollY > SizeUtils.dp2px(5))) {// 下拉超过10dp
//                    showTitleBar(false);
//                }
            }
        });

        scroll_view.setScrollViewListener(new MyNestedScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(MyNestedScrollView scrollView, int x, int y, int oldx, int oldy) {
//                Logg.i("y = " + y + ",topHeight = " + topHeight + ",pageHeight = " + pageHeight);
                if (y > topHeight) {// 滑动超过了顶部(banner + menu + 左右俩图)
                    rl_tab.setVisibility(View.VISIBLE);
                } else {
                    rl_tab.setVisibility(View.GONE);
                }
            }
        });
        tab.addOnTabSelectedListener(new OnTabSelectedListenerImpl() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                setTabFragment(tab);
                tab_2.getTabAt(tab.getPosition()).select();
            }
        });
        tab_2.addOnTabSelectedListener(new OnTabSelectedListenerImpl() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                Home2Fragment.this.tab.getTabAt(tab.getPosition()).select();
            }
        });

        setOnClickListener(scan_layout, ll_search, msg_layout, iv_new_1, iv_new_2);
    }

    @Override
    public void onClick(View view) {
        if (view == msg_layout) {
            startActivity(MsgActivity.class);
        }
        if (view == scan_layout) {
//            startActivity(ProductDetailActivity.class);
        }
        if (view == ll_search) {// 搜索
            startActivity(SearchActivity.class);
        }
        if (view == iv_new_1) {

        }
        if (view == iv_new_2) {// 优惠券
            startActivity(CouponListActivity.class);
        }
    }

    // 根据tab切换fragment
    private void setTabFragment(XTabLayout.Tab tab) {
        scroll_view.post(new PageHeightRunnable());// 计算页面高度
        int tabIndex = tab.getPosition();
        if (tabIndex == 0) {
            getFragmentManager().beginTransaction().replace(R.id.rl_container, HomePro0Fragment.newInstance(Home2Fragment.this), "fragment0").commitNowAllowingStateLoss();
            Arad.bus.post(new EventModel(19110750, homeData));
        }
        if (tabIndex == 1) {
            getFragmentManager().beginTransaction().replace(R.id.rl_container, HomePro1Fragment.newInstance(Home2Fragment.this), "fragment1").commitNowAllowingStateLoss();
            Arad.bus.post(new EventModel(19110751, homeData));
        }
        if (tabIndex == 2) {
            getFragmentManager().beginTransaction().replace(R.id.rl_container, HomePro2Fragment.newInstance(), "fragment2").commitNowAllowingStateLoss();
            Arad.bus.post(new EventModel(19110752, homeData));
        }
        if (tabIndex == 3) {
            getFragmentManager().beginTransaction().replace(R.id.rl_container, HomePro3Fragment.newInstance(), "fragment3").commitNowAllowingStateLoss();
            Arad.bus.post(new EventModel(19110753, homeData));
        }
        if (tabIndex == 4) {
            getFragmentManager().beginTransaction().replace(R.id.rl_container, HomePro4Fragment.newInstance(), "fragment4").commitNowAllowingStateLoss();
            Arad.bus.post(new EventModel(19110754, homeData));
        }
    }

    private void initBanner(final List<Advert> bannerList) {
        List<String> urlList = new ArrayList<>();//图片地址集合
        List<String> introList = new ArrayList<>();//简介集合
        if (!isDataEmpty(bannerList)) {
            for (Advert banner : bannerList) {
                urlList.add(banner.getImgUrl());
                introList.add("");//不显示banner简介
            }
        }
        if (isDataEmpty(urlList)) {
            banner.setVisibility(View.GONE);
            iv_banner_holder.setVisibility(View.VISIBLE);
            return;
        } else {
            banner.setVisibility(View.VISIBLE);
            iv_banner_holder.setVisibility(View.GONE);
        }
        try {
            banner.setImages(urlList);//设置图片集合
            banner.setImageLoader(new GlideImageLoader());//设置图片加载器
            banner.setDelayTime(6000);//设置轮播时间
            banner.setIndicatorGravity(BannerConfig.RIGHT);
            banner.setBannerAnimation(Transformer.Accordion);
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int pos) {
                    ToastUtils.showShortSafe("点击广告banner" + pos);
                }
            });
            banner.start();//banner设置方法全部调用完毕时最后调用
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ScrollInfo scrollInfo = new ScrollInfo();// 封装滑动信息

    private void showTitleBar(boolean isShow) {
        if (isShow) {
            if (home_title_bar_layout.getVisibility() == View.GONE) {
                home_title_bar_layout.setVisibility(View.VISIBLE);
            }
        } else {
            if (home_title_bar_layout.getVisibility() == View.VISIBLE) {
                home_title_bar_layout.setVisibility(View.GONE);
            }
        }
    }

    //banner下面的菜单项的adapter
    private static class MenuAdapter extends ListBaseAdapter<Model> {

        private int[] menuIcon = {R.drawable.home_ic_menu_4_dfts, R.drawable.home_ic_menu_0_tyt
                , R.drawable.home_ic_menu_1_gyg, R.drawable.home_ic_menu_2_chj, R.drawable.home_ic_menu_3_cjqc
                , R.drawable.home_ic_menu_5_hyjp, R.drawable.home_ic_menu_6_tjsp, R.drawable.home_ic_menu_7_jjsj
                , R.drawable.home_ic_menu_8_yhq, R.drawable.home_ic_menu_9_grzx};

        public MenuAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.home_item_menu;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int pos) {
            TextView tv_menu_txt = holder.getView(R.id.tv_menu_txt);
            ImageView iv_menu_icon = holder.getView(R.id.iv_menu_icon);

            Model model = mDataList.get(pos);
            tv_menu_txt.setText(model.getTitle());
            iv_menu_icon.setImageResource(menuIcon[pos]);
        }
    }

    // 计算首页顶部高度
    private class TopHeightRunnable implements Runnable {
        @Override
        public void run() {
            int bannerHei = banner.getMeasuredHeight();
            int menuHei = rcv_10_menu.getMeasuredHeight();
            int imgHei = iv_new_1.getMeasuredHeight();
            int margin = SizeUtils.dp2px(20);
            topHeight = bannerHei + menuHei + imgHei + margin;
        }
    }

    // 计算首页高度
    private class PageHeightRunnable implements Runnable {
        @Override
        public void run() {
            pageHeight = scroll_view.getMeasuredHeight();
        }
    }

    public void setOnGetDataListener(OnGetDataListener onGetDataListener) {
        this.onGetDataListener = onGetDataListener;
    }

    OnGetDataListener onGetDataListener;

    // 父层获得数据的监听
    public interface OnGetDataListener {
        void onGetData(Object data, int position);
    }
}
